﻿using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using K9Nano.Updater.Client.ViewModels;
using K9Nano.Updater.Extensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace K9Nano.Updater.Client;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    readonly MainWindowViewModel _vm;

    public MainWindow()
    {
        InitializeComponent();
        _vm = IocHelper.ServiceProvider.GetRequiredService<MainWindowViewModel>();
        _vm.ReportLogging = OnLogging;
        this.DataContext = _vm;
        this.Closing += MainWindow_Closing;
    }

    private void OnLogging(LogLevel level, string message)
    {
        WriteLog("Main", level, message);
    }

    public void WriteLog(string category, LogLevel level, string message)
    {
        if (string.IsNullOrEmpty(message)) return;
        var lines = message.ToLines();
        if (lines.Count <= 0) return;

        Brush color = level switch
        {
            LogLevel.Trace => Brushes.DarkGray,
            LogLevel.Debug => Brushes.DarkGray,
            LogLevel.Information => Brushes.Black,
            LogLevel.Warning => Brushes.Orange,
            LogLevel.Error => Brushes.Red,
            LogLevel.Critical => Brushes.DarkRed,
            _ => Brushes.DarkGray
        };      

        this.Dispatcher.InvokeAsync(() =>
        {
            var p = new Paragraph();
            var timeRun = new Run(DateTime.Now.ToString("HH:mm:ss") + "  ")
            {
                Foreground = Brushes.Gray
            };
            p.Inlines.Add(timeRun);
            p.Inlines.Add(new Run(lines[0]) { Foreground = color });

            // 第二行
            var intend = new string(' ', 10);
            for (var i = 1; i < lines.Count; i++)
            {
                p.Inlines.Add(new LineBreak());
                p.Inlines.Add(new Run(intend + lines[i]) { Foreground = color });
            }
            this.Console.Document.Blocks.Add(p);
            this.Console.ScrollToEnd();
        });
    }

    private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
    {
        if (!_vm.CanClose)
        {
            e.Cancel = true;
        }
    }
}